<template>
  <div class="page-main">
    <el-breadcrumb class="breadcrumb">
      <el-breadcrumb-item>管理员</el-breadcrumb-item>
      <el-breadcrumb-item>商铺管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="main-content">
      <div class="box-card">
        <span style="color: #101010; font-size: 16px">商铺管理</span>
      </div>
      <div class="box-body">
        <div class="search">
          <div style="margin-top: 20px">
            <el-input
                placeholder="请输入商店名"
                prefix-icon="el-icon-search"
                v-model="status.keywords"
                style="width: 250px; margin-right: 20px"
                clearable
                @keyup.enter="getShopList"
                @clear="getShopList"
            />
            <el-select v-model="status.backCateName" @change="getShopList">
              <el-option label="全部" :value="null"/>
              <el-option v-for="item in status.backCateNameOptions" :key="item.value" :label="item.value" :value="item.value"/>
            </el-select>
            <el-select v-model="status.state" @change="getShopList" style="margin-left: 20px">
              <el-option label="全部" :value="null"/>
              <el-option label="待审核" :value="1"/>
              <el-option label="已上架" :value="2"/>
              <el-option label="已下架" :value="3"/>
            </el-select>
            <el-button
                type="primary"
                icon="el-icon-search"
                @click="getShopList()"
                style="margin-left: 10px"
            >
              搜索
            </el-button>
          </div>
        </div>
        <div class="table">
          <el-table :data="status.shopList" style="width: 100%">
            <el-table-column type="index" align="center" />
            <el-table-column label="商店封面" align="center">
              <template #default="scope">
                <img :src="scope.row['frontImgUrl']" />
              </template>
            </el-table-column>
            <el-table-column prop="shopId" label="商店Id" align="center" />
            <el-table-column prop="shopName" label="商店名" align="center" />
            <el-table-column prop="shopPhone" label="联系电话" align="center" />
            <el-table-column label="状态" align="center">
              <template #default="scope">
                <div v-if="scope.row.state === 1">待审核</div>
                <div v-else-if="scope.row.state === 2">已上架</div>
                <div v-else-if="scope.row.state === 3">已下架</div>
              </template>
            </el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                align="center"
                width="100"
            >
              <template #default="scope">
                <el-button type="text" @click="showDetail(scope.row)">详情</el-button>
                <el-button type="text" style="margin-left: 20px" v-if="scope.row.state !== 1" @click="goMealList(scope.row.shopId)">菜品</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="page-div">
          <el-pagination
              v-model:currentPage="pageStatus.currentPage"
              v-model:page-size="pageStatus.pageSize"
              :page-sizes="[5, 10, 20]"
              :pager-count="5"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageStatus.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
  <el-dialog
      v-model="shopDialog.showFlag"
      title="订单详情"
      width="50%"
      :before-close="closeShopDialog"
  >
    <div>
      <el-form
          ref="refForm"
          label-position="right"
          label-width="120px"
          :model="shopDialog.data"
          :rules="status.rules"
          :disabled="shopDialog.data.state !== 2"
      >
        <el-form-item label="商店ID" disabled="" prop="shopName">
          <el-input disabled v-model="shopDialog.data.shopId" />
        </el-form-item>
        <el-form-item label="店主ID" prop="shopName">
          <el-input disabled v-model="shopDialog.data.ownerId" />
        </el-form-item>
        <el-form-item label="商店名称" prop="shopName">
          <el-input v-model="shopDialog.data.shopName" />
        </el-form-item>
        <el-form-item label="商店类型" prop="backCateName">
          <el-select v-model="shopDialog.data.backCateName" filterable>
            <el-option
                v-for="item in status.backCateNameOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商店电话" prop="shopPhone">
          <el-input v-model="shopDialog.data.shopPhone" />
        </el-form-item>
        <el-form-item label="自动接单">
          <el-switch disabled v-model="shopDialog.data.autoAcceptOrder" />
        </el-form-item>
        <el-form-item label="商店LOGO">
          <div class="logo-div">
            <div class="logo-area">
              <img :src="shopDialog.data.frontImgUrl" class="logoImg"/>
            </div>
            <div class="upload-button-div">
              <el-button style="height: 50px" @click="changeToCommon">
                <div class="button">
                  <img src="@/assets/img/shopInfo/img.png" />
                  <span>改为默认</span>
                </div>
              </el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="商店地址" prop="shopAddress">
          <el-input v-model="shopDialog.data.shopAddress" />
        </el-form-item>
        <el-form-item label="具体位置" prop="latitude">
          <baidu-map :info="baiduMapInfo" @mark="setOrgPosition"></baidu-map>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <template v-if="shopDialog.data.state === 1">
          <el-button type="primary" @click="suspendConfirm(suspendTheShop)">下架</el-button>
          <el-button type="primary" @click="continueConfirm(continueTheShop)">上架</el-button>
        </template>
        <template v-if="shopDialog.data.state === 2">
          <el-button type="primary" @click="suspendConfirm(suspendTheShop)">下架</el-button>
          <el-button type="primary" @click="managerUpdateShopInfo">确定</el-button>
        </template>
        <template v-if="shopDialog.data.state === 3">
          <el-button type="primary" @click="continueConfirm(continueTheShop)">上架</el-button>
          <el-button type="primary" @click="managerUpdateShopInfo">确定</el-button>
        </template>
      </span>
    </template>
  </el-dialog>
  <confirm-dialog
      ref="confirmDialogRef"
      :info="info"
      @handleConfirm="handleConfirm"
      @cancelConfirm="cancelConfirm"
  ></confirm-dialog>
</template>

<script setup>
import BaiduMap from "@/components/BaiduMap";
import {onMounted, reactive, ref} from "vue";
import {httpPostManage} from "@/api/httpService";
import {Debounce} from "@/tool";
import ConfirmDialog from "@/components/ConfirmDialog";
import {ElMessage} from "element-plus";
import router from "@/router";

const confirmDialogRef = ref(null);

const refForm = ref(null);

const status = reactive({
  keywords: "",
  backCateName: null,
  backCateNameOptions: [],
  state: null,
  shopList: [],
  rules: {
    shopName: [
      { required: true, message: "请输入商店名字", trigger: "blur" }
    ],
    backCateName: [
      { required: true, message: "请选择商店类型", trigger: "blur" }
    ],
    shopPhone: [
      { required: true, message: "请输入商店电话", trigger: "blur" }
    ],
    shopAddress: [
      { required: true, message: "请输入商店地址", trigger: "blur" }
    ],
    latitude: [
      { required: true, message: "请选择商店的定位", trigger: "blur" }
    ]
  }
});

const shopDialog = reactive({
  showFlag: false,
  data: {
    shopId: "",
    shopName: "",
    ownerId: "",
    backCateName: "",
    shopPhone: "",
    shopAddress: "",
    frontImgUrl: "https://img.yzcdn.cn/vant/custom-empty-image.png",
    latitude: "",
    longitude: "",
    state: ""
  }
});

const baiduMapInfo = reactive({
  type: "preview",
  lat: "",
  lon: ""
});

const getAllBackCateName = async () => {
  let url = "/getAllBackCateName";
  let res = await httpPostManage(url, {});
  res.data.forEach((item) => {
    let it = {
      label: item,
      value: item
    }
    status.backCateNameOptions.push(it);
  });
}

const getShopList = async () => {
  let url = "/searchAllShop";
  let params = {
    keywords: status.keywords,
    type: status.backCateName,
    state: status.state,
    currentPage: pageStatus.currentPage,
    pageSize: pageStatus.pageSize
  }
  let res = await httpPostManage(url, params);
  status.shopList = res.data.data;
  pageStatus.total = res.data.total;
}

const goMealList = (id) => {
  router.push({
    path: "/manager/mealManager",
    query: {
      id: id
    }
  })
}

/**
 * shopDialog模块
 * **/
const showDetail = (item) => {
  for (let p in shopDialog.data) {
    shopDialog.data[p] = item[p];
  }
  baiduMapInfo.lat = item.latitude;
  baiduMapInfo.lon = item.longitude;
  shopDialog.showFlag = true;
}

const managerUpdateShopInfo = () => {
  refForm["value"].validate(async (valid) => {
    if (valid) {
      let url = "/managerUpdateShopInfo";
      let res = await httpPostManage(url, shopDialog.data);
      if(res.data === "修改成功") {
        ElMessage.success("修改成功");
      }
      await getShopList();
      closeShopDialog();
    }
  });
}

const closeShopDialog = () => {
  refForm.value.resetFields();
  let obj = {
    shopId: "",
    shopName: "",
    ownerId: "",
    backCateName: "",
    shopPhone: "",
    shopAddress: "",
    frontImgUrl: "https://img.yzcdn.cn/vant/custom-empty-image.png",
    latitude: "",
    longitude: "",
    state: ""
  }
  shopDialog.data = obj;
  shopDialog.showFlag = false;
}

const suspendTheShop = async (id) => {
  let url = "/suspendTheShop";
  let params = {
    shopId: id
  }
  await httpPostManage(url, params);
  await getShopList();
  ElMessage.success("下架成功")
  cancelConfirm();
  closeShopDialog();
}

const continueTheShop = async (id) => {
  let url = "/continueTheShop";
  let params = {
    shopId: id
  }
  await httpPostManage(url, params);
  await getShopList();
  ElMessage.success("上架成功")
  cancelConfirm();
  closeShopDialog();
}

const suspendConfirm = Debounce((methodName) => {
  shopDialog.showFlag = false;
  info.title = "确定你的操作";
  info.content = "是否确定要下架" + shopDialog.data.shopName + "这一商铺?";
  info.methodName = methodName;
  info.methodParams["methodId"] = shopDialog.data.shopId;
  confirmDialogRef["value"].makeDialogVisible();
});

const continueConfirm = Debounce((methodName) => {
  shopDialog.showFlag = false;
  info.title = "确定你的操作";
  info.content = "是否确定要上架" + shopDialog.data.shopName + "这一商铺?";
  info.methodName = methodName;
  info.methodParams["methodId"] = shopDialog.data.shopId;
  confirmDialogRef["value"].makeDialogVisible();
});

const changeToCommon = () => {
  shopDialog.data.frontImgUrl = "https://img.yzcdn.cn/vant/custom-empty-image.png"
}

/**
 * confirmDialog模块
 **/
const info = reactive({
  title: "",
  content: "",
  methodName: "",
  methodParams: {}
});

const handleConfirm = Debounce(function (dialogInfo) {
  dialogInfo.methodName(dialogInfo.methodParams.methodId);
  info.title = "";
  info.content = "";
  info.methodName = "";
  info.methodParams = {};
});

const cancelConfirm = () => {
  info.title = "";
  info.content = "";
  info.methodName = "";
  info.methodParams = {};
  shopDialog.showFlag = true;
};

/**设置机构位置 */
const setOrgPosition = (point) => {
  shopDialog.data.latitude = point.lat;
  shopDialog.data.longitude = point["lng"];
};

/**
 * 分页模块
 **/
//#region 分页模块
const pageStatus = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

//改变每页页数
const handleSizeChange = (val) => {
  pageStatus.pageSize = val;
  getShopList();
};

//改变当前页
const handleCurrentChange = (val) => {
  pageStatus.currentPage = val;
  getShopList();
};

onMounted(async () => {
  await getAllBackCateName();
  await getShopList();
});
</script>

<style lang="scss" scoped>
@import "../../assets/style/layout.scss";
</style>